package com.future.mayi.activity;

import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.model.AddressModel;
import com.future.mayi.model.CateModel;
import com.future.mayi.model.KeepGoodsModel;
import com.future.mayi.model.NewCateOrderModel;
import com.future.mayi.model.OrderServiceListModel;
import com.future.mayi.model.RedPacketModel;
import com.future.mayi.model.SellerAddressModel;
import com.future.mayi.response.RedPackResponse;
import com.future.mayi.response.SellerAddressResponse;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.PriceUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 新建鉴定或养护订单
 */
public class NewAppraisalOrderActivity extends BaseTitleActivity {
    @BindView(R.id.tv_sub_title)
    TextView tvSubTitle;
    @BindView(R.id.ll_appraisal_goods)
    LinearLayout llAppraisalGoods;
    @BindView(R.id.tv_jijian_name)
    TextView tvJijianName;
    @BindView(R.id.tv_jijian_phone)
    TextView tvJijianPhone;
    @BindView(R.id.tv_jijian_address)
    TextView tvJijianAddress;
    @BindView(R.id.ll_jijian)
    LinearLayout llJijian;

    @BindView(R.id.tv_huiji_name)
    TextView tvHuijiName;
    @BindView(R.id.tv_huiji_phone)
    TextView tvHuijiPhone;
    @BindView(R.id.tv_huiji_address)
    TextView tvHuijiAddress;
    @BindView(R.id.ll_huiji)
    LinearLayout llHuiji;
    @BindView(R.id.tv_huiji_add_address)
    TextView tvHuijiAddAddress;
    @BindView(R.id.tv_add_red_packet)
    TextView tvAddRedPacket;
    @BindView(R.id.tv_red_packet)
    TextView tvRedPacket;
    @BindView(R.id.tv_appraisal_price)
    TextView tvAppraisalPrice;
    @BindView(R.id.tv_red_packet_price)
    TextView tvRedPacketPrice;
    @BindView(R.id.tv_prompt)
    TextView tvPrompt;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_enter)
    TextView tvEnter;

    private LayoutInflater mInflater;
    private List<CateModel> cateModelList;
    private KeepGoodsModel keepGoodsModel;
    private double money;
    private double subMoney;
    private SellerAddressModel jijianModel;
    private AddressModel huijiModel;
    private List<RedPacketModel> redPacketModels;

    private int orderType;
    private String userRedpackId;

    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("确认订单");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_new_appraisal_order);
    }

    @Override
    protected void initView() {

        if (getIntent() != null) {
            if (getIntent().getSerializableExtra("list") != null)
                cateModelList = (List<CateModel>) getIntent().getSerializableExtra("list");
            money = getIntent().getDoubleExtra("money", 0);
            keepGoodsModel = (KeepGoodsModel) getIntent().getSerializableExtra("keep");
        }
        if ((cateModelList == null || cateModelList.size() == 0) && keepGoodsModel == null)
            return;

        mInflater = LayoutInflater.from(this);
        tvAppraisalPrice.setText("¥" + PriceUtils.getPriceText2(money));
        tvMoney.setText(PriceUtils.getPriceText2(money - subMoney));


        if (cateModelList != null) {
            orderType = 1;
            View viewLine = null;
            for (CateModel model : cateModelList) {
                View view = mInflater.inflate(R.layout.layout_appraisal_goods_item, llAppraisalGoods, false);
                ImageView ivImg = (ImageView) view.findViewById(R.id.iv_img);
                TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
                TextView tvGoodsPrice = (TextView) view.findViewById(R.id.tv_goods_price);
                TextView tvGoodsNum = (TextView) view.findViewById(R.id.tv_goods_num);
                viewLine = view.findViewById(R.id.view_line);
                HCUtils.loadWebImg(this, ivImg, model.getCate_img());
                tvTitle.setText(model.getCate_name());
                tvGoodsPrice.setText(PriceUtils.getPriceText2(model.getPrice()));
                tvGoodsNum.setText((String.valueOf(model.getNum())));
                llAppraisalGoods.addView(view);
            }
            if (viewLine != null) viewLine.setVisibility(View.GONE);
            tvPrompt.setText(getResources().getString(R.string.new_appraisal_order_hint));
        }

        if (keepGoodsModel != null) {
            orderType = 2;
            tvSubTitle.setText("养护商品");
            View view = mInflater.inflate(R.layout.layout_appraisal_goods_item, llAppraisalGoods, false);
            ImageView ivImg = (ImageView) view.findViewById(R.id.iv_img);
            TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
            TextView tvGoodsPrice = (TextView) view.findViewById(R.id.tv_goods_price);
            TextView tvGoodsNum = (TextView) view.findViewById(R.id.tv_goods_num);

            View viewLine = view.findViewById(R.id.view_line);
            viewLine.setVisibility(View.GONE);
            HCUtils.loadWebImg(this, ivImg, keepGoodsModel.getType_img());
            tvTitle.setText(keepGoodsModel.getType_name());
            tvGoodsPrice.setText(PriceUtils.getPriceText2(keepGoodsModel.getPrice()));
            tvGoodsNum.setText((String.valueOf(1)));
            llAppraisalGoods.addView(view);
            tvPrompt.setText(getResources().getString(R.string.new_keep_order_hint));
        }

    }

    @Override
    protected void initDates() {
        getAllRedPacket();
        setJijian();
        refreshSellerAddress();
        setHuiji();
        refreshAddress();
    }

    @Override
    protected void initListener() {

    }


    @OnClick({R.id.ll_select_huiji, R.id.tv_add_red_packet, R.id.tv_enter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_select_huiji: {
                Intent intent = new Intent(this, AddressActivity.class);
                intent.putExtra("isSelect", true);
                startActivityForResult(intent, 222);
            }
            break;
            case R.id.tv_add_red_packet:
                String goods = "";
                if (keepGoodsModel != null) {
                    goods = String.valueOf(keepGoodsModel.getType_id());
                } else if (cateModelList != null && cateModelList.size() > 0) {
                    for (CateModel model : cateModelList) {
                        goods = goods + model.getCate_id() + ",";
                    }
                    if (goods.length() > 1)
                        goods = goods.substring(0, goods.length() - 1);
                }
                SelectReadPacketActivity.startActivity(this, money, goods);
                break;
            case R.id.tv_enter:
                tvEnter.setEnabled(false);
                if (!enter())
                    tvEnter.setEnabled(true);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
                if (requestCode == 222) {
                    huijiModel = (AddressModel) data.getSerializableExtra("model");
                    setHuiji();
                } else if (requestCode == 234) {
                    if (data.getSerializableExtra("redPacket") == null)
                        redPacketModels = null;
                    else
                        redPacketModels = (List<RedPacketModel>) data.getSerializableExtra("redPacket");
                    setRedPacketView();
                } else if (requestCode == 215) {
                    finish();
                }
            }
        }
    }

    private boolean enter() {


        if (huijiModel == null) {
            toast("请选择回寄地址");
            return false;
        }

        NewCateOrderModel model = new NewCateOrderModel();
        model.setAddress_id(huijiModel.getAddress_id());
        model.setOrder_type(orderType);
        List<OrderServiceListModel> listModels = new ArrayList<>();
        if (orderType == 1 && cateModelList != null) {
            for (CateModel cateModel : cateModelList) {
                OrderServiceListModel orderServiceListModel = new OrderServiceListModel();
                orderServiceListModel.setBuy_num(cateModel.getNum());
                orderServiceListModel.setCate_id(cateModel.getCate_id());
                orderServiceListModel.setGoods_name(cateModel.getCate_name());
                listModels.add(orderServiceListModel);
            }
        } else if (keepGoodsModel != null) {
            OrderServiceListModel orderServiceListModel = new OrderServiceListModel();
            orderServiceListModel.setBuy_num(1);
            orderServiceListModel.setCate_id(keepGoodsModel.getType_id());
            orderServiceListModel.setGoods_name(keepGoodsModel.getType_name());
            listModels.add(orderServiceListModel);
        }

        String service_list = App.getGson().toJson(listModels);
        model.setService_list(service_list);
        model.setUser_redpack_id(userRedpackId);
        return true;
    }

    private void setRedPacketView() {
        subMoney = 0d;
        userRedpackId = "";
        if (redPacketModels == null || redPacketModels.size() == 0) {
            tvRedPacket.setText("");
            tvRedPacketPrice.setText("");
            tvMoney.setText(PriceUtils.getPriceText2(money - subMoney));
            return;
        }

        for (RedPacketModel redPacketModel : redPacketModels) {
            subMoney = subMoney + redPacketModel.getPar_value();
            userRedpackId = userRedpackId + redPacketModel.getUser_redpack_id() + ",";
        }
        if (userRedpackId.length() > 1)
            userRedpackId = userRedpackId.substring(0, userRedpackId.length() - 1);

        String subM = "-¥ " + PriceUtils.getPriceText2(subMoney);
        tvRedPacket.setText(subM);
        tvRedPacketPrice.setText(subM);
        tvMoney.setText(PriceUtils.getPriceText2(money - subMoney));
    }

    private void setJijian() {
        if (jijianModel == null) return;
        tvJijianName.setText(jijianModel.getUser());
        tvJijianPhone.setText(jijianModel.getTel());
        tvJijianAddress.setText(jijianModel.getAddress());
    }

    private void setHuiji() {
        if (huijiModel == null) {
            llHuiji.setVisibility(View.GONE);
            tvHuijiAddAddress.setVisibility(View.VISIBLE);
        } else {
            llHuiji.setVisibility(View.VISIBLE);
            tvHuijiAddAddress.setVisibility(View.GONE);

        }
    }


    private void refreshSellerAddress() {
        new HttpRequest<SellerAddressResponse>()
                .with(this)
                .setApiCode(ApiCst.getSellerAddress)
                .addParam("key", orderType == 1 ? "jd" : "yh")//关键字 jd-鉴定 yh-养护 jm-寄卖 hs-回收 默认不传为jd
                .setListener(new HttpRequest.OnNetworkListener<SellerAddressResponse>() {
                    @Override
                    public void onSuccess(SellerAddressResponse response) {
                        jijianModel = response.getAddressModel();
                        setJijian();
                    }

                    @Override
                    public void onFail(String message, SellerAddressResponse response) {
                        toast(message);
                    }
                })
                .start(new SellerAddressResponse());
    }

    private void getAllRedPacket() {
        new HttpRequest<RedPackResponse>()
                .with(this)
                .setApiCode(ApiCst.getRedpackList)
                .addParam("status", 0)
                .addParam("p", 0)
                .addParam("psize", 1000)
                .addParam("token", App.getToken(mContext))
                .setListener(new HttpRequest.OnNetworkListener<RedPackResponse>() {
                    @Override
                    public void onSuccess(RedPackResponse response) {
                        int size = (response.getList() == null || response.getList().size() == 0) ? 0 : response.getList().size();
                        if (size == 0)
                            tvRedPacket.setHint("暂无可用");
                        else
                            tvRedPacket.setHint(size + "个可用");
                        tvRedPacket.setText("");
                    }

                    @Override
                    public void onFail(String message, RedPackResponse response) {

                    }
                }).start(new RedPackResponse());
    }

    //加载默认地址
    private void refreshAddress() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        tvEnter.setEnabled(true);
    }
}
